const router = require('koa-router')()
const fs = require('fs')
const path = require('path')
const mongoose = require('mongoose')

router.post('/', async (ctx) => {
  // image 是前端传过来的name值
  console.log('upload')
  // console.log(ctx.request)

  try {
    const file = ctx.request.files.image // 获取上传文件

    const reader = fs.createReadStream(file.path)
    const filePath = path.join(__dirname, '../public/uploads') + `/${file.name}`
    // 创建可写流
    const upStream = fs.createWriteStream(filePath)
    // 可读流通过管道写入可写流
    reader.pipe(upStream)
    const webpath = filePath.split('public')[1]
    // 将文件存放到数据库里
    const table = mongoose.model('bee')
    try {
      await table.findOneAndUpdate({ phone: ctx.session.phone }, { protrait: webpath }, { useFindAndModify: false })
      console.log('更新成功')
      ctx.body = {
        code: 200,
        webpath,
        msg: '上传成功'
      }
    } catch (err) {
      console.log('更新失败')
    }
  } catch (err) {
    console.log(err)
    ctx.body = {
      code: 500,
      msg: '上传失败'
    }
  }
})

module.exports = router
